package com.vcc.msc.sbs;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.vcc.msc.sbs.adapter.ShowResultExpandableListViewAdapter;
import com.vcc.msc.sbs.entity.SessionAttributesEntity;
import com.vcc.msc.sbs.entity.WesEntity;
import com.vcc.msc.sbs.proxy.ServiceLocator;
import com.vcc.msc.sbs.proxy.SessionAttributesProxy;
import com.vcc.msc.sbs.proxy.WesProxy;

public class WesActivity extends ParentActivity {
	private Spinner typeCode;
	private AutoCompleteTextView wesId;
	private WesProxy wesProxy;
	private SessionAttributesProxy sessionAttributesProxy;
	private ExpandableListView listView;
	ShowResultExpandableListViewAdapter adapter;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wes);

		// TODO Fix VCC Proxy settings or set it via resource file.
		// Settings.System.putString(getContentResolver(),
		// Settings.System.HTTP_PROXY, "10.254.96.30:83");

		// TODO - Use thread for WS calls.
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);

		typeCode = (Spinner) findViewById(R.id.dropdown_TypeCode);

		wesId = (AutoCompleteTextView) findViewById(R.id.autocomplete_wesId);

		sessionAttributesProxy = ServiceLocator.getSessionAttributesProxy();
		SessionAttributesEntity sessionAttributes = sessionAttributesProxy
				.getSessionAttributes(false);

		ArrayAdapter<String> dropdownArray_adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item,
				sessionAttributes.getTypeCodeList());
		typeCode.setAdapter(dropdownArray_adapter);
		typeCode.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {

			}

			public void onNothingSelected(AdapterView<?> parent) {
				// do nothing
			}
		});

		wesProxy = ServiceLocator.getWesProxy();

		ArrayAdapter<String> autoCompleteArray_adapter_WesId = new ArrayAdapter<String>(
				this, R.layout.list_item, wesProxy.getWesIds(typeCode
						.getSelectedItem().toString()));
		wesId.setAdapter(autoCompleteArray_adapter_WesId);

		listView = (ExpandableListView) findViewById(R.id.expandableListViewResult);
	}

	/**
	 * On click WES Search button.
	 * 
	 * @param view
	 */
	public void wesSearch(View view) {
		// Hide soft keyboard
		InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

		// Un-hide Result header
		TableRow headerRow = (TableRow) findViewById(R.id.table_resultHeader);
		headerRow.setVisibility(View.VISIBLE);

		// Hide search area
		TableRow searchArea = (TableRow) findViewById(R.id.table_searchArea);
		searchArea.setVisibility(View.GONE);
		ImageButton buttonSearchBox = (ImageButton) findViewById(R.id.button_searchBox);
		buttonSearchBox.setVisibility(View.VISIBLE);

		String typeCodeValue = typeCode.getSelectedItem().toString();
		String wesIdValue = wesId.getText().toString();

		// TODO WS Call under thread
		List<WesEntity> wesList = wesProxy.getWesList("PROD", typeCodeValue,
				wesIdValue);

		// Initialize the adapter with wesList
		adapter = new ShowResultExpandableListViewAdapter(this, wesList);

		// Set adapter to the list view
		listView.setAdapter(adapter);
	}

	public void unhideSearbox(View view) {
		TableRow searchArea = (TableRow) findViewById(R.id.table_searchArea);
		searchArea.setVisibility(View.VISIBLE);
		ImageButton buttonSearchBox = (ImageButton) findViewById(R.id.button_searchBox);
		buttonSearchBox.setVisibility(View.INVISIBLE);
	}

	// TODO use system constants
	private static final int CAMERA_PIC_REQUEST = 1337;
	private static final int SELECT_PICTURE = 1;

	/**
	 * On Click Add image on WES result view
	 * 
	 * @param view
	 */
	public void onClickAddImg(View view) {
		final CharSequence[] items = { "Open", "Capture" };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				switch (item) {
				case 0:
					Intent intent = new Intent();
					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					startActivityForResult(
							Intent.createChooser(intent, "Select Picture"),
							SELECT_PICTURE);
					break;
				case 1:
					Intent cameraIntent = new Intent(
							android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
				}
			}
		}).show();

	}

	private String filePath;

	/**
	 * Dependent call back method for {@code onClickAddImg}
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
			Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
			ImageView image = (ImageView) findViewById(R.id.photoResultView);
			image.setImageBitmap(thumbnail);
		} else if (resultCode == RESULT_OK) {

			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			filePath = cursor.getString(columnIndex);
			cursor.close();

			Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
			ImageView image = (ImageView) findViewById(R.id.photoResultView);
			image.setImageBitmap(yourSelectedImage);

		}

	}

	/**
	 * On click image full screen
	 * 
	 * @param view
	 */
	public void onClickImgFullScr(View view) {
		Dialog d;
		d = new Dialog(this, android.R.style.Theme_InputMethod);
		d.setContentView(R.layout.full_image);
		ImageView imageSrc = (ImageView) view;
		ImageView imageDes = (ImageView) d.findViewById(R.id.fullImage);
		imageDes.setBackgroundDrawable(imageSrc.getDrawable());
		d.show();
		WindowManager.LayoutParams lp = d.getWindow().getAttributes();
		lp.dimAmount = 0.7f;
		d.getWindow().setAttributes(lp);
		d.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
	}

	/**
	 * On click Edit WES Description
	 * 
	 * @param view
	 */
	public void onClickEditWesDescription(View view) {
		Log.d(this.getClass().getName(), "onClickEditWesDescription");

		View parent = (View) view.getParent();
		final TextView resultWesName = (TextView) parent
				.findViewById(R.id.resultWesName);
		AlertDialog.Builder alert = new AlertDialog.Builder(this,
				R.style.editTextDialog);

		alert.setTitle("Edit Wes description");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setText(resultWesName.getText());
		input.setHeight(200);
		input.setWidth(1000);
		input.setGravity(Gravity.TOP);
		input.setSelection(resultWesName.getText().length());
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String newValue = input.getText().toString();
				resultWesName.setText(newValue);
				Log.d(this.getClass().getName(), "-------" + newValue);
			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();

	}

	// private Handler handler = new Handler() {
	//
	// @Override
	// public void handleMessage(Message msg) {
	// adapter.notifyDataSetChanged();
	// super.handleMessage(msg);
	// }
	//
	// };

}
